<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <!-- import CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/element-ui@2.15.3/lib/theme-chalk/index.css"
    integrity="sha256-ghr1zmXTODLKl1HULQd6fq1MIe7m3FJiNTOCT8sddLM=" crossorigin="anonymous">
  <style>
    .el-image__inner.el-image__inner {
      width: 100%;
      height: 90px;
    }

    .el-image {
      text-align: center;
    }

    .el-button+.el-button {
      margin: 0;
    }
  </style>
  <script src="https://js.sentry-cdn.com/219f636ac7bde5edab2c3e16885cb535.min.js" crossorigin="anonymous"></script>
</head>

<body>
  <div id="app">
    <el-container>
      <el-header>
        <div style="
         margin: auto;
         line-height: 60px;
         font-size: xx-large;
         position: relative;
     ">Dashboard


          <span style="
     position: absolute;
     right: 0px;
      ">
            <a href="./admin-imgtc.html">
              <el-button size="mini" type="warning">网格视图</el-button>
            </a>
            <a href="./admin-waterfall.html">
              <el-button size="mini" type="primary">瀑布流</el-button>
            </a>
            <el-button v-if="showLogoutButton" size="mini" type="info" @click="handleLogout()">退出登录</el-button></span>
        </div>
      </el-header>
      <el-main><el-row :gutter="12">
          <el-col :span="24">
            <el-card shadow="always">
              记录总数量:
              {{ Number }}
            </el-card>
          </el-col>
          <!--<el-col :span="8">
              <el-card shadow="hover">
                <el-tooltip class="item" effect="dark" content="白名单数量" placement="top-start">
                   
                </el-tooltip>
                白名单数量：{{ WhiteList }}
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover">
                <el-tooltip class="item" effect="dark" content="黑名单数量" placement="top-start">
                
              </el-tooltip>
              黑名单数量：{{ BlackList }}
              </el-card>
            </el-col>-->
        </el-row>
        <template>
          <el-table :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
            style="width: 100%">
            <el-table-column label="name" prop="name">
            </el-table-column>
            <el-table-column label="preview" prop="preview" align="center">
              <template slot-scope="scope">
                <video v-if="scope.row.name.indexOf('.mp4')>0" style="width: 100%; height: 180px;" controls>
                  <source :src="'/file/'+scope.row.name" type="video/mp4">
                </video>
                <el-image v-else style="width: 100%; height: 100%;" :src="'/file/'+scope.row.name" :zoom-rate="1.2"
                  :preview-src-list="['/file/'+scope.row.name]" fit="cover" lazy />

              </template>
            </el-table-column>
            <el-table-column label="data" prop="data">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <p>{{ scope.row.metadata }}</p>
                  <div slot="reference" class="name-wrapper">
                    <el-tag size="medium">{{ scope.row.metadata }}</el-tag>
                  </div>
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column align="right">
              <template slot="header" slot-scope="scope">
                <el-input v-model="search" @input="handleSearch" size="mini" placeholder="输入关键字搜索" />
              </template>
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="handleCopy(scope.$index,scope.row.name)">复制地址</el-button>
                <el-button size="mini" type="primary" @click="handleWhite(scope.$index,scope.row.name)">白名单</el-button>
                <el-button size="mini" type="info" @click="handleBlock(scope.$index,scope.row.name)">黑名单</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row.name)">删除</el-button>
              </template>
            </el-table-column>
            </el-table>
            <el-button v-if="nextCursor" style="margin-top:16px" @click="loadMore">加载更多</el-button>
          </template>
        </el-main>
    </el-container>
  </div>
</body>
<!-- import Vue before Element -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"
  integrity="sha256-kXTEJcRFN330VirZFl6gj9+UM6gIKW195fYZeR3xDhc=" crossorigin="anonymous"></script>
<!-- import JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/element-ui@2.15.3/lib/index.js"
  integrity="sha256-OFVFYfqhQ9nDnKh+NfIsefpy/fnjTwkK909ZYgo45nw=" crossorigin="anonymous"></script>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      Number: 0,
      WhiteList: 0,
        BlackList: 0,
        showLogoutButton: false,
        tableData: [],
        nextCursor: null,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      form: {
        name: '',
        id: ''
      },
      search: '',
      password: '123456',
      searchTimer: null
    },
    methods: {
      handleBlock(index, key) {
        console.log(key);
        if (confirm("确认加入黑名单吗?")) {
          console.log("Yes")
          var requestOptions = {
            method: 'GET',
            redirect: 'follow',
            //include authorization credientials
            credentials: 'include'
          };

          fetch("./api/manage/block/" + key, requestOptions)
            .then(response => response.text())
            .then(result => {
              console.log(result);
              this.tableData[index].metadata = result;
            })
            .catch(error => { alert("An error occurred while synchronizing data with the server, please check the network connection"); console.log('error', error) });

        } else {
          console.log("No")
        }
      },
      handleDelete(index, key) {
        console.log(key);
        if (confirm("确认删除该条记录吗?")) {
          console.log("Yes")
          var requestOptions = {
            method: 'GET',
            redirect: 'follow',
            //include authorization credientials
            credentials: 'include'
          };

          fetch("./api/manage/delete/" + key, requestOptions)
            .then(response => response.text())
            .then(result => { console.log(result); this.tableData.remove(index); })
            .catch(error => { alert("An error occurred while synchronizing data with the server, please check the network connection"); console.log('error', error) });

        } else {
          console.log("No")
        }
      },
      handleWhite(index, key) {
        console.log(key);
        if (confirm("确认加入白名单吗?")) {
          console.log("Yes")
          var requestOptions = {
            method: 'GET',
            redirect: 'follow',
            //include authorization credientials
            credentials: 'include'
          };
          fetch("./api/manage/white/" + key, requestOptions)
            .then(response => response.text())
            .then(result => { console.log(result); this.tableData[index].metadata = result; })
            .catch(error => { alert("An error occurred while synchronizing data with the server, please check the network connection"); console.log('error', error) });

        } else {
          console.log("No")
        }

      },
      handleLogout() {
        window.location.href = "./api/manage/logout";
      },
      handleCopy(index, key) {
        const text = `${document.location.origin}/file/${key}`;
        if (navigator.clipboard) {
          // clipboard api 复制
          navigator.clipboard.writeText(text);
        } else {
          const textarea = document.createElement('textarea');
          document.body.appendChild(textarea);
          // 隐藏此输入框
          textarea.style.position = 'fixed';
          textarea.style.clip = 'rect(0 0 0 0)';
          textarea.style.top = '10px';
          // 赋值
          textarea.value = text;
          // 选中
          textarea.select();
          // 复制
          document.execCommand('copy', true);
          // 移除输入框
          document.body.removeChild(textarea);
        }
        this.$message({
          message: '复制文件链接成功~',
          type: 'success'
        });
      },
      handleSearch() {
        clearTimeout(this.searchTimer);
        this.searchTimer = setTimeout(() => {
          this.tableData = [];
          this.nextCursor = null;
          const opts = { method: 'GET', redirect: 'follow', credentials: 'include' };
          const base = this.search
            ? `./api/manage/list?limit=100&prefix=${encodeURIComponent(this.search)}`
            : `./api/manage/list?limit=100`;
          fetch(base, opts)
            .then(r => r.json())
            .then(result => {
              this.tableData = result.keys || [];
              this.nextCursor = result.list_complete ? null : result.cursor;
              this.Number = this.tableData.length;
            })
            .catch(() => alert("搜索失败，请检查网络"));
        }, 300);
      },
      loadMore() {
        const opts = { method: 'GET', redirect: 'follow', credentials: 'include' };
        const base = this.search
          ? `./api/manage/list?limit=100&prefix=${encodeURIComponent(this.search)}`
          : `./api/manage/list?limit=100`;
        const url = this.nextCursor
          ? `${base}&cursor=${encodeURIComponent(this.nextCursor)}`
          : base;

        fetch(url, opts)
          .then(r => r.json())
          .then(result => {
            this.tableData = this.tableData.concat(result.keys || []);
            this.nextCursor = result.list_complete ? null : result.cursor;
            this.Number = this.tableData.length;
          })
          .catch(() => alert("同步失败，请检查网络"));
      },
    },

    mounted() {
      //check if the user is logged in
      //read the basic auth credientials from the browser
      var requestOptions = {
        method: 'GET',
        redirect: 'follow',
        //include authorization credientials
        credentials: 'include'
      };
      fetch("./api/manage/check", requestOptions)
        .then(response => response.text())
        .then(result => {
          console.log(result);
          if (result == "true") {
            this.showLogoutButton = true;
          } else if (result == "Not using basic auth.") {

          }
          else {
            window.location.href = "./api/manage/login";
          }
        })
        .catch(error => { alert("An error occurred while synchronizing data with the server, please check the network connection"); console.log('error', error) });



      Array.prototype.remove = function (from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
      };
      var requestOptions = {
        method: 'GET',
        redirect: 'follow',
        //include authorization credientials
        credentials: 'include'

      };


        fetch("./api/manage/list?limit=100", requestOptions)
        //判断是否需要登录
        .then(response => {
          if (response.status == 401) {
            alert("请先登录");
            window.location.href = "./api/manage/login";
          }
          else {
            return response;
          }
        })
        .then(response => response.json())
        .then(result => {
          this.tableData = result.keys || [];
          this.nextCursor = result.list_complete ? null : result.cursor;
          console.log(result);
          this.Number = this.tableData.length;
        })
        .catch(error => { alert("An error occurred while synchronizing data with the server, please check the network connection"); console.log('error', error) });

    }
  })

</script><!-- Hotjar Tracking Code -->
<script>
    (function (h, o, t, j, a, r) {
      h.hj = h.hj || function () { (h.hj.q = h.hj.q || []).push(arguments) };
      h._hjSettings = { hjid: 2531461, hjsv: 6 };
      a = o.getElementsByTagName('head')[0];
      r = o.createElement('script'); r.async = 1;
      r.src = t + h._hjSettings.hjid + j + h._hjSettings.hjsv;
      a.appendChild(r);
    })(window, document, 'https://static.hotjar.com/c/hotjar-', '.js?sv=');
</script>
<script type="text/javascript">
  (function (c, l, a, r, i, t, y) {
    c[a] = c[a] || function () { (c[a].q = c[a].q || []).push(arguments) };
    t = l.createElement(r); t.async = 1; t.src = "https://www.clarity.ms/tag/" + i;
    y = l.getElementsByTagName(r)[0]; y.parentNode.insertBefore(t, y);
  })(window, document, "clarity", "script", "7t5ai7agat");
</script>

</html>